package com.klaus.ohMySpace.sys.intercepter;

import com.klaus.ohMySpace.conf.Constants;
import com.klaus.ohMySpace.service.TokenService;
import com.klaus.ohMySpace.sys.common.ErrorCode;
import com.klaus.ohMySpace.util.JsonUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

import static com.klaus.ohMySpace.util.Params.getString;

/**
 * Created by Mklaus on 15/8/16.
 */
public class AuthorizeIntercepter implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;

    private List<String> user_Authorization;
    private List<String> app_user_Authorization;

    public void setUser_Authorization(List<String> user_Authorization) {
        this.user_Authorization = user_Authorization;
    }

    public void setApp_user_Authorization(List<String> app_user_Authorization) {
        this.app_user_Authorization = app_user_Authorization;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
        System.out.println("can intercepter. url = " + req.getRequestURI());
        String request_uri = new String(req.getRequestURI());

        for (String uri : user_Authorization){
            if (request_uri.endsWith(uri)){
                if (req.getSession().getAttribute(Constants.USER_UID) != null){
                    return true;
                }else {
                    throw new AuthorizationException("in interceptor");
                }
            }
        }

        for (String uri : app_user_Authorization){
            if (request_uri.endsWith(uri)){
                String deviceId = getString(req, "deviceId" );
                String token    = getString(req, "token"    );
                if (tokenService.isPass(token,deviceId)){
                    return true;
                }else{
                    JsonUtil.writeError(ErrorCode.needLogin, "happen in interceptor", resp);
                    req.setAttribute("error",ErrorCode.needLogin);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        return;
    }
}
